#include "formalbummixer.h"
#include "ui_formalbummixer.h"

#include <QFileDialog>
#include <QListWidgetItem>
#include <QPixmap>
#include <QDirIterator>
#include <QStringList>


FormAlbumMixer::FormAlbumMixer(CProfile *pProfile, QWidget *parent) :
    QWidget(parent), m_pProfile(pProfile),
    m_ui(new Ui::FormAlbumMixer)
{
    m_ui->setupUi(this);

    m_bIsModified = false;

    doReshape();
}

FormAlbumMixer::~FormAlbumMixer()
{
    delete m_ui;
}

void FormAlbumMixer::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void FormAlbumMixer::on_pushButtonSrcDir_clicked()
{

    QString strDir = QFileDialog::getExistingDirectory(this, tr("Open Source Directory"),
                      "", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

    if(!strDir.isEmpty())
    {
        m_ui->lineEditSrcDirectory->setText(strDir);
        m_ui->pushButtonPreview->setEnabled(true);
    }
}

void FormAlbumMixer::on_pushButtonDstDir_clicked()
{
    QString strDir = QFileDialog::getExistingDirectory(this, tr("Open Destination Directory"),
                      "", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

    if(!strDir.isEmpty())
    {
        m_ui->lineEditOutDirectory->setText(strDir);
        m_ui->pushButtonProcess->setEnabled(true);
    }
}

void FormAlbumMixer::on_listWidgetFiles_currentRowChanged(int currentRow)
{
    int nHeigh = m_ui->labelPictureOutput->minimumHeight();
    int nWidth = m_ui->labelPictureOutput->minimumWidth();
    QListWidgetItem * item = m_ui->listWidgetFiles->item(currentRow);
    if(item)
    {
        Log(QString("Scalling %1 to %2x%3").arg(item->text()).arg(nWidth).arg(nHeigh));
        m_ui->labelPictureOutput->setPixmap(QPixmap(item->text()).scaled(nWidth, nHeigh, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    }
    m_ui->progressBar->setValue(currentRow+1);
}

void FormAlbumMixer::on_pushButtonPreview_clicked()
{
    m_bIsModified = true;
    // clear data
    m_ui->listWidgetFiles->clear();
    m_ui->listWidgetLog->clear();
    m_strlistFilesCache.clear();
    m_ui->progressBar->setValue(0);

    QString strSrcDir(m_ui->lineEditSrcDirectory->text());
    Log(QString("Genrating preview for %1 ...").arg(strSrcDir));
    QStringList nameFilters;
    nameFilters << "*.jpg";
    QDirIterator it(strSrcDir, nameFilters, QDir::AllEntries | QDir::Files | QDir::NoDotAndDotDot,
                    QDirIterator::Subdirectories);
    while (it.hasNext())
        m_strlistFilesCache << it.next();

    m_nFilesCacheSize = m_strlistFilesCache.count();
    m_ui->progressCache->setMaximum(m_nFilesCacheSize);

    /* initialize random seed: */
    srand ( time(NULL) );

    int nMaxEntryNumber = m_pProfile->m_nMaxFiles < m_strlistFilesCache.count() ? m_pProfile->m_nMaxFiles : m_strlistFilesCache.count();
    while(nMaxEntryNumber--)
    {
        QListWidgetItem *pItem = new QListWidgetItem(ExtractOneRandomFilename(), m_ui->listWidgetFiles, QListWidgetItem::Type);
        pItem->setIcon(QIcon(":/images/kontact_contacts.png"));
    }

    m_ui->progressBar->setMaximum(m_ui->listWidgetFiles->count());
    m_ui->listWidgetFiles->setCurrentRow(0);
    m_ui->pushButtonDstDir->setEnabled(true);
    m_ui->progressBar->setValue(m_ui->progressBar->maximum());

    Log("Done");
}

void FormAlbumMixer::on_pushButtonProcess_clicked()
{
    m_ui->pushButtonSrcDir->setEnabled(false);
    m_ui->pushButtonDstDir->setEnabled(false);
    m_ui->pushButtonPreview->setEnabled(false);
    m_ui->pushButtonProcess->setEnabled(false);

    int nHeigh = m_pProfile->m_nHeight;
    int nWidth = m_pProfile->m_nWidth;
    m_ui->progressBar->setMaximum(m_ui->listWidgetFiles->count());
    Log("Processing files ...");

    int nStartNumber = m_pProfile->n_nStartNumber;
    for(int iRow = 0; iRow < m_ui->listWidgetFiles->count(); iRow++)
    {
        if(m_pProfile->m_bEnablePreviewWhileProcessing)
            m_ui->listWidgetFiles->setCurrentRow(iRow);
        QListWidgetItem *pItem = m_ui->listWidgetFiles->item(iRow);
        //QFileInfo fileInfo(pItem->text());
        //QString strOutputName(QString("%1/%2").arg(m_ui->lineEditOutDirectory->text()).arg(fileInfo.fileName()));
        QString strOutputName(QString("%1/pimi%2.jpg").arg(m_ui->lineEditOutDirectory->text()).arg(nStartNumber++, 4, 10, QChar('0')));
        QPixmap(QPixmap(pItem->text()).scaled(nWidth, nHeigh, Qt::KeepAspectRatio, Qt::SmoothTransformation)).save(strOutputName, "JPG", m_pProfile->m_nImageQuality);
        m_ui->progressBar->setValue(iRow+1);
        Log(QString("Processed %1 -> %2, scaled %3x%4, quality %5").arg(pItem->text()).arg(strOutputName).arg(nWidth).arg(nHeigh).arg(m_pProfile->m_nImageQuality));
    }

    m_ui->pushButtonSrcDir->setEnabled(true);
    m_ui->pushButtonDstDir->setEnabled(true);
    m_ui->pushButtonPreview->setEnabled(true);
    m_ui->pushButtonProcess->setEnabled(true);
}

void FormAlbumMixer::on_listWidgetFiles_doubleClicked(QModelIndex index)
{
    actionDelete();
}

void FormAlbumMixer::actionDelete()
{
    m_bIsModified = true;
    QListWidgetItem * pCurrent = m_ui->listWidgetFiles->currentItem();
    int currentRow = m_ui->listWidgetFiles->currentRow();
    if(pCurrent)
    {
        QString strNewFileName = ExtractOneRandomFilename();
        if(!strNewFileName.isEmpty())
        {
            Log(QString("File %1 replaced to %2").arg(pCurrent->text()).arg(strNewFileName));
            pCurrent->setText(strNewFileName);
        }
        else
        {
            Log(QString("File %1 deleted from list").arg(pCurrent->text()));
            m_ui->listWidgetFiles->removeItemWidget(pCurrent);
        }
    }
    on_listWidgetFiles_currentRowChanged(currentRow);
}

#define PIMI_DATAFILESIGNATURE "e8db14be-ce96-4691-9f21-4e4d763e9251"
void FormAlbumMixer::actionSave()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                                "", tr("Pimi file(*.pimi)"));

    if(fileName.isEmpty())
    {
        Log("Save canceled");
        return;
    }

    // open data file
    QFile file(fileName);
    if(!file.open(QIODevice::WriteOnly))
    {
        Log(QString("Unable to open %1 to save data").arg(fileName));
        return;
    }
    // we will serialize the data into the file
    QDataStream out(&file);

    int nCurrentRow = m_ui->listWidgetFiles->currentRow();
    QStringList strlistFiles;

    for(int iRow = 0; iRow < m_ui->listWidgetFiles->count(); iRow++)
    {
        QListWidgetItem *pItem = m_ui->listWidgetFiles->item(iRow);
        strlistFiles << pItem->text();
    }

    out << QString(PIMI_DATAFILESIGNATURE);
    out << nCurrentRow;
    out << strlistFiles;
    out << m_nFilesCacheSize;
    out << m_strlistFilesCache;  // save cache

    m_bIsModified = false;

    Log(QString("Saved to %1").arg(fileName));
}

void FormAlbumMixer::actionLoad()
{

    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                "", tr("Pimi file(*.pimi)"));

    if(fileName.isEmpty())
    {
        Log("Load canceled");
        return;
    }

    // open data file
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly))
    {
        Log(QString("Unable to open %1 to save data").arg(fileName));
        return;
    }
    // we will serialize the data into the file
    QDataStream in(&file);

    QString strFileSignature;
    int nCurrentRow;
    QStringList strlistFiles;

    in >> strFileSignature;
    if(strFileSignature != PIMI_DATAFILESIGNATURE)
    {
        Log(QString("Data file %1 signature is not correct").arg(fileName));
        return;
    }
    // reset controls
    m_ui->pushButtonSrcDir->setEnabled(true);
    m_ui->pushButtonDstDir->setEnabled(true);
    m_ui->pushButtonPreview->setEnabled(false);
    m_ui->pushButtonProcess->setEnabled(false);

    in >> nCurrentRow;
    in >> strlistFiles;
    in >> m_nFilesCacheSize;
    in >> m_strlistFilesCache;

    m_ui->listWidgetFiles->clear();
    for(int iRow = 0; iRow < strlistFiles.count(); iRow++)
    {
        QListWidgetItem *pItem = new QListWidgetItem(strlistFiles.at(iRow), m_ui->listWidgetFiles, QListWidgetItem::Type);
        pItem->setIcon(QIcon(":/images/kontact_contacts.png"));
    }

    m_ui->listWidgetFiles->setCurrentRow(nCurrentRow);

    // restore cache progress bar
    m_ui->progressCache->setMaximum(m_nFilesCacheSize);
    m_ui->progressCache->setValue(m_strlistFilesCache.count());

    Log(QString("Loaded from %1").arg(fileName));
}

void FormAlbumMixer::doReshape()
{
    m_ui->labelPictureOutput->setMinimumSize(QSize(m_pProfile->m_nWidthPreview, m_pProfile->m_nHeightPreview));
    m_ui->labelPictureOutput->setMaximumSize(QSize(m_pProfile->m_nWidthPreview, m_pProfile->m_nHeightPreview));
}

bool FormAlbumMixer::isModified() const
{
    return m_bIsModified;
}

QString FormAlbumMixer::ExtractOneRandomFilename()
{
    m_bIsModified = true;
    QString strFileName;
    if(m_strlistFilesCache.size())
    {
        int iIdx = (int)(((double)rand()/RAND_MAX) * m_strlistFilesCache.size());
        strFileName = m_strlistFilesCache.at(iIdx);
        m_strlistFilesCache.removeAt(iIdx);
    }

    m_ui->progressCache->setValue(m_strlistFilesCache.count());

    return strFileName;
}

void FormAlbumMixer::Log(QString strLogData) const
{
    QListWidgetItem *pItem = new QListWidgetItem(strLogData, m_ui->listWidgetLog, QListWidgetItem::Type);
    m_ui->listWidgetLog->setCurrentItem(pItem);
    QCoreApplication::processEvents();
    //m_ui->listWidgetLog->repaint();
}
